package linkedList;

public class MaxTwin {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

    }

    public  int pairSum(ListNode head) {
        if (head == null || head.next == null) {
            return 0; // 如果链表为空或只有一个节点，则最大孪生和为 03333333333
        }

        int n = countNodes(head); // 计算链表长度
        int[] values = new int[n]; // 用数组存储链表节点的值

        // 将链表节点的值存储到数组中
        ListNode curr = head;
        int index = 0;
        while (curr != null) {
            values[index++] = curr.val;
            curr = curr.next;
        }

        int maxTwinSum = 0;

        // 计算节点及其孪生节点值之和的最大值
        for (int i = 0; i < n / 2; i++) {
            int twinSum = values[i] + values[n - 1 - i];
            if (twinSum > maxTwinSum) {
                maxTwinSum = twinSum;
            }
        }

        return maxTwinSum;
    }

    //计算链表长度
    private int countNodes(ListNode head) {
        int count = 0;
        ListNode curr = head;
        while (curr != null) {
            count++;
            curr = curr.next;
        }
        return count;
    }
    public static void main(String[] args) {
        // 示例用法
        ListNode head = new ListNode(0);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);

        MaxTwin maxTwin = new MaxTwin();
        int result = maxTwin.pairSum(head);
        System.out.println("Maximum Twin Sum: " + result); // 输出最大孪生和
    }
}

